package net.goutalk.glcs.module.authority.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.goutalk.glcs.common.constant.GlobalConstant;
import net.goutalk.glcs.common.utils.RedisUtil;
import net.goutalk.glcs.module.authority.entity.DataAuthTableRelation;
import net.goutalk.glcs.module.authority.mapper.DataAuthTableRelationMapper;
import net.goutalk.glcs.module.authority.service.IDataAuthTableRelationService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 数据权限 与 表 关联关系表 服务实现类
 * </p>
 *
 * @author tanyujie
 * @since 2023-02-28
 */
@Service
@AllArgsConstructor
public class DataAuthTableRelationServiceImpl extends ServiceImpl<DataAuthTableRelationMapper, DataAuthTableRelation> implements IDataAuthTableRelationService {

    private final RedisUtil redisUtil;

    @Override
    public Boolean saveDataAuthTableRelations(String tableName, List<Long> dataAuthIdList) {
        List<DataAuthTableRelation> toSaveList = new ArrayList<>();
        // 先删除原有的关联关系
        boolean isRemoved = this.remove(Wrappers.<DataAuthTableRelation>query().lambda().eq(DataAuthTableRelation::getTableName, tableName));
        boolean isSuccessAdd = false;
        if (CollectionUtils.isNotEmpty(dataAuthIdList)) {
            for (Long id : dataAuthIdList) {
                DataAuthTableRelation item = new DataAuthTableRelation();
                item.setDataAuthId(id);
                item.setTableName(tableName);
                toSaveList.add(item);
            }
            isSuccessAdd = this.saveBatch(toSaveList);
        }
        if (isRemoved || isSuccessAdd) {
            // 更新缓存
            List<DataAuthTableRelation> list = this.list();
            redisUtil.set(GlobalConstant.DATA_AUTH_TABLE_RELATION_CACHE_KEY, list);
        }
        return isSuccessAdd;
    }
}
